繼上回介紹如何透過 Laravel 讀取與產出 Excel 檔案之後,
我們這次來介紹如何透過 mPDF 這個套件來產生 PDF 檔案。
composer require mpdf/mpdf
由於 mPDF 是以 HTML 轉換成 PDF,
所以我們需要先建立一個 Blade 模板,例如:resources/views/pdf/report.blade.php
你可以在這個 Blade 中使用標準 HTML + Blade 語法來排版內容。
渲染 Blade 成 HTML 字串
use Illuminate\Support\Facades\View;
$html = View::make("pdf.$htmlName", ['parameter' => $fileData])->render();
"pdf.$htmlName":會去找 resources/views/pdf/{檔名}.blade.php
$fileData:傳進 Blade 模板的資料
use Mpdf\Mpdf;
$mpdf = new Mpdf([
'mode' => 'utf-8', // 使用 UTF-8 編碼,支援多語系文字
'format' => 'A3', // 紙張大小:A3(也可用 A4、Letter)
'orientation' => 'L', // L:橫向(Landscape),P:直向(Portrait)
'autoScriptToLang' => true, // 自動判斷語系
'autoLangToFont' => true, // 自動切換合適字型(如中文使用中文字型)
'margin_bottom' => 0, // 下邊界設為 0,排版更自由
]);
$mpdf->WriteHTML($html);
$mpdf->Output($filePath, 'F');
'F' 表示儲存成檔案